package com.example.springbootquartz.listener;
import com.example.springbootquartz.config.MyQuartzScheduler;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.impl.StdSchedulerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.event.ContextRefreshedEvent;

/**
 * Created by IntelliJ IDEA2022.3.2
 * @Author: Tenghw
 * @Date: 2023/08/05  12:55
 * @Description: 事件监听器
 */
@Configuration
public class ApplicationStartQuartzJobListener implements ApplicationListener<ContextRefreshedEvent> {

    @Lazy //延迟加载,解决循环依赖的问题
    @Autowired
    MyQuartzScheduler myQuartzScheduler;

    //项目启动时，也启动quartz
    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        try {
            myQuartzScheduler.startAllJobs();
        } catch (SchedulerException e) {
            throw new RuntimeException(e);
        }
        System.out.println("定时任务已经启动...");
    }
    /**
     * 注入scheduler

     */
    @Bean
    public Scheduler scheduler() throws SchedulerException{
        SchedulerFactory schedulerFactoryBean = new StdSchedulerFactory();
        return schedulerFactoryBean.getScheduler();
    }


}
